package com.sheep.spark.job.impl;

import com.sheep.spark.job.FileStreamJob;
import com.sheep.spark.job.NetworkStreamJob;
import org.apache.log4j.Logger;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import scala.Tuple2;

import java.util.Arrays;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 16-6-2
 * Time: 上午11:27
 * To change this template use File | Settings | File Templates.
 */
public class ErrorLogAnalysisJobByNetwork extends NetworkStreamJob {
    private static final Logger logger = Logger.getLogger(ErrorLogAnalysisJobByNetwork.class);

    private static final Pattern SPACE = Pattern.compile(" ");

    @Override
    public void run(JavaReceiverInputDStream<String> lines) {
        //To change body of implemented methods use File | Settings | File Templates.
        JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterable<String> call(String x) throws Exception {
                return Arrays.asList(SPACE.split(x));  //To change body of implemented methods use File | Settings | File Templates.
            }
        });
        JavaPairDStream<String, Integer> wordCounts = words.mapToPair(
                new PairFunction<String, String, Integer>() {
                    @Override
                    public Tuple2<String, Integer> call(String s) {
                        return new Tuple2<String, Integer>(s, 1);
                    }
                }).reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer i1, Integer i2) {
                return i1 + i2;
            }
        });

        wordCounts.print();
    }
}
